
package net.swa.dewei.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Required;

import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.dewei.service.MenDianService;
import net.swa.system.beans.entity.User;
import net.swa.system.service.ICommonService;
import net.swa.system.util.SysConst;
import net.swa.system.util.annotation.Log;
import net.swa.system.web.action.AbstractBaseAction;
import net.swa.util.DateUtils;
import net.swa.util.JsonResult;
import net.swa.util.StringUtil;

/** 门店信息表 Action **/
public class MenDianAction extends AbstractBaseAction
{
    private static final long serialVersionUID = 1908627223355967719L;

    private static final Logger log = Logger.getLogger(MenDianAction.class);

    private MenDianService menDianService;

    private MenDian model;

    // 实体类id
    private Long id;

    // 批量删除的id集合
    private Long[] ids;

    private Boolean isAdmin;

    /** 当前用户若是服务站，其服务站id **/
    private Long fuwuzhanId;

    /* 原来的微信id* */
    private String oldWxid;

    private String nickname;

    private String fuwuzhanName;

    private String name;

    private String address;

    private String lxr;

    //是否充电站
    private Boolean ischarge;

    private Boolean weixiu;

    private Boolean xiaoshou;

    private Boolean mobiCharge;

    private File file;

    private String fileFileName;

    /** 公用方法接口 */
    private ICommonService commonService;

    /** 初始化分页查询 **/
    @Log(description = "初始化门店分页查询")
    public String listPage()
    {
        User user = getCurrentUser();
        if (null != user)
        {
            if (SysConst.USER_TYPE_FUWUZHAN == user.getUserType())
            {
                fuwuzhanId = user.getFuwuzhanId();
            }
            else
            {
                fuwuzhanId = null;
            }
        }
        //        ischarge = true;
        //        weixiu = true;
        //        xiaoshou = true;
        return "listPage";
    }

    /**门店分页查询**/
    public String queryMendianPage() throws Exception
    {
        currentPage = currentPage == 0 ? 1 : currentPage;
        pageSize = pageSize == 0 ? 20 : pageSize;
        JsonResult<MenDian> json = null;
        json = menDianService.queryExtMendianPage(name, nickname, fuwuzhanId, fuwuzhanName, ischarge, weixiu, xiaoshou, mobiCharge, currentPage, pageSize, orderBy, orderType);
        json.setCurrentPage(currentPage);
        outJson(json);
        return null;
    }

    /**门店分页查询
     * 查询信息主要做选择使用
     * 支持根据服务站、门店、门店地址、门店联系人，昵称查询
     * @return
     * @throws Exception
     */
    public String queryMendianPageList() throws Exception
    {
        currentPage = currentPage == 0 ? 1 : currentPage;
        pageSize = pageSize == 0 ? 20 : pageSize;
        JsonResult<MenDian> json = null;
        json = menDianService.queryExtMendianPageList(name, nickname, fuwuzhanId, fuwuzhanName, address, lxr, ischarge, weixiu, xiaoshou, mobiCharge, currentPage, pageSize, orderBy, orderType);
        json.setCurrentPage(currentPage);
        outJson(json);
        return null;
    }

    public String zhiding()
    {
        return "zhiding";
    }

    /** 去新增或者修改页面 **/
    @Log(description = "去新增或者修改门店")
    public String toAddMenDian() throws Exception
    {
        FuwuZhan fuwuzhan = null;
        User user = getCurrentUser();
        if (null != user)
        {
            if (null != id)
            {
                if (SysConst.USER_TYPE_ADMIN == user.getUserType())
                {
                    isAdmin = true;
                }
                else
                {
                    isAdmin = false;
                }
                model = commonService.commonFind(MenDian.class, id);
                if (null != model)
                {
                    if (null != model.getFuwuzhanId())
                    {
                        fuwuzhan = commonService.commonFind(FuwuZhan.class, model.getFuwuzhanId());
                        if (null != fuwuzhan)
                        {
                            model.setFuwuzhanName(fuwuzhan.getName());
                        }
                    }
                    if (null != model.getWxid())
                    {
                        WeixinInfo wx = commonService.findByAttribute(WeixinInfo.class, "id", model.getWxid());
                        if (null != wx)
                        {
                            model.setNickname(wx.getNickname());
                        }
                    }
                }
            }
            else
            {
                model = new MenDian();
                if (SysConst.USER_TYPE_ADMIN == user.getUserType())
                {
                    isAdmin = true;
                }
                else if (SysConst.USER_TYPE_FUWUZHAN == user.getUserType())
                {
                    isAdmin = false;
                    if (null != user.getFuwuzhanId())
                    {
                        fuwuzhan = commonService.commonFind(FuwuZhan.class, user.getFuwuzhanId());
                        if (null != fuwuzhan)
                        {
                            model.setFuwuzhanName(fuwuzhan.getName());
                            model.setFuwuzhanId(fuwuzhan.getId());
                        }
                    }
                }
            }
            return "toAddMenDian";
        }
        else
        {
            return LOGIN;
        }

    }

    /** 新增或者修改 **/
    @Log(description = "保存门店，到数据库")
    public String saveMenDian() throws Exception
    {
        JsonResult<String> json = new JsonResult<String>();
        boolean isadmin = false;
        User u = getCurrentUser();
        if (null != u)
        {
            if (SysConst.USER_TYPE_ADMIN == u.getUserType())
            {
                isadmin = true;
            }
        }
        if (null == model.getId())
        {
            model.setCrateDate(DateUtils.getCurrDate(null));
            json = menDianService.addModel(model, isadmin);
        }
        else
        {
            model.setUpdateDate(DateUtils.getCurrDate(null));
            json = menDianService.updateModel(model, oldWxid, isadmin);
        }
        outJson(json);
        return null;
    }

    /** * 删除方法 **/
    @Log(description = "删除门店")
    public String delete() throws Exception
    {
        menDianService.delete(ids);
        outSuccess();
        return null;
    }

    /**删除门店，平板接口**/
    public String deleteMenDian() throws Exception
    {
        log.debug("平板接口调用，删除门店信息：" + ids);
        boolean f = menDianService.delete(ids);
        if (f)
        {
            log.debug("平板接口调用，成功完成删除门店信息");
            outSuccess();
        }
        else
        {
            outError("操作出错");
        }
        return null;
    }

    /** 根据县查询所有门店 **/
    public String getShops() throws Exception
    {
        String xian = getRequestParameter("xian");
        List<MenDian> list = commonService.search("town", xian, MenDian.class);
        outJson(list);
        return null;
    }

    /** 根据门店id 查询门店 */
    public String queryById() throws Exception
    {
        if (null != id)
        {
            model = commonService.commonFind(MenDian.class, id);
            if (null != model)
            {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("success", true);
                map.put("model", model);
                outJson(map);
            }
            else
            {
                outError("cant not find");
            }
        }
        else
        {
            outError("id is null");
        }
        return null;
    }

    /** 跳转到微信号选择页面 */
    public String weixinList()
    {

        return "weixinList";
    }

    public String exportExcel()
    {
        //根据多条件导出
        HSSFWorkbook workbook = menDianService.exportExcel(name, nickname, fuwuzhanId, fuwuzhanName, address, lxr, ischarge, weixiu, xiaoshou, mobiCharge);
        HttpServletResponse response = getResponse();
        BufferedOutputStream bos = null;
        try
        {
            response.setContentType("application/vnd.ms-excel");
            String filename = new String("filename".getBytes("gbk"), "iso-8859-1") + ".xls";
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            bos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bos);
            bos.flush();
            removeSessionAttribute("listSheet");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.debug("门店导出出错：" + e);
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String exportTemplate()
    {
        String path = getSession().getServletContext().getRealPath("/templates/mendian.xls");
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String exportErrorFile()
    {
        String path = getSession().getServletContext().getRealPath("/templates/mendian.xls");
        if (!StringUtils.isBlank(fileFileName))
        {
            path = fileFileName;
        }
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentLength((int) file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String toImpMendExcel()
    {

        return "import";
    }

    public String impMendExcel() throws Exception
    {
        Map<String, Object> map = null;
        String errFilePath = ServletActionContext.getServletContext().getRealPath("/uploads/error/");
        if (null != file && (!file.toString().equals("")))
        {
            String path = uploadFile();
            if (!StringUtils.isBlank(path))
            {
                map = menDianService.addExcel(path, errFilePath);
            }
            else
            {
                map = new HashMap<String, Object>();
                map.put("success", false);
                map.put("message", "文件上传失败");
            }
        }
        else
        {
            map = new HashMap<String, Object>();
            map.put("success", false);
            map.put("message", "请选择按模板格式的文件上传");
        }
        outJson(map);
        return null;
    }

    /**
     * 上传文件
     * @return
     */
    private String uploadFile()
    {
        String code = StringUtil.getRandomString(5) + System.currentTimeMillis();
        String realpath = ServletActionContext.getServletContext().getRealPath("/uploads/");
        try
        {
            File saveFile = new File(new File(realpath), fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls");
            if (saveFile.exists())
            {
                saveFile.delete();
            }
            file.renameTo(saveFile);
            return realpath + File.separator + fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls";
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "false";
    }

    public Boolean getIsAdmin()
    {
        return isAdmin;
    }

    public void setIsAdmin(Boolean isAdmin)
    {
        this.isAdmin = isAdmin;
    }

    public Long getFuwuzhanId()
    {
        return fuwuzhanId;
    }

    public void setFuwuzhanId(Long fuwuzhanId)
    {
        this.fuwuzhanId = fuwuzhanId;
    }

    public ICommonService getCommonService()
    {
        return commonService;
    }

    public String getOldWxid()
    {
        return oldWxid;
    }

    public void setOldWxid(String oldWxid)
    {
        this.oldWxid = oldWxid;
    }

    @Required
    @Resource
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    public Long getId()
    {

        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public Long[] getIds()
    {
        return ids;
    }

    public void setIds(Long[] ids)
    {
        this.ids = ids;
    }

    public MenDian getModel()
    {
        return model;
    }

    public void setModel(MenDian model)
    {
        this.model = model;
    }

    @Required
    @Resource
    public void setMenDianService(MenDianService menDianService)
    {
        this.menDianService = menDianService;
    }

    public String getNickname()
    {
        return nickname;
    }

    public void setNickname(String nickname)
    {
        this.nickname = nickname;
    }

    public String getFuwuzhanName()
    {
        return fuwuzhanName;
    }

    public void setFuwuzhanName(String fuwuzhanName)
    {
        this.fuwuzhanName = fuwuzhanName;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    public String getLxr()
    {
        return lxr;
    }

    public void setLxr(String lxr)
    {
        this.lxr = lxr;
    }

    public Boolean getIscharge()
    {
        return ischarge;
    }

    public void setIscharge(Boolean ischarge)
    {
        this.ischarge = ischarge;
    }

    public Boolean getWeixiu()
    {
        return weixiu;
    }

    public void setWeixiu(Boolean weixiu)
    {
        this.weixiu = weixiu;
    }

    public Boolean getXiaoshou()
    {
        return xiaoshou;
    }

    public void setXiaoshou(Boolean xiaoshou)
    {
        this.xiaoshou = xiaoshou;
    }

    public File getFile()
    {
        return file;
    }

    public void setFile(File file)
    {
        this.file = file;
    }

    public String getFileFileName()
    {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName)
    {
        this.fileFileName = fileFileName;
    }

    public Boolean getMobiCharge()
    {
        return mobiCharge;
    }

    public void setMobiCharge(Boolean mobiCharge)
    {
        this.mobiCharge = mobiCharge;
    }

}
